https://leetcode.com/problems/move-zeroes/
Given an array nums
, write a function to move all 0
's to the end of it while maintaining the relative order of the non-zero elements.
Example:
Example:
Input: [0,1,0,3,12]
Output: [1,3,12,0,0]
Note:
public class Solution {
public void MoveZeroes(int[] nums) {
int pointer = 0;
for (int i = 0; i < nums.Length; i++)
{
if (nums[i] != 0)
{
if (pointer != i)
{
nums[pointer] = nums[i];
nums[i] = 0;
}
pointer++;
}
}
}
}
Runtime: 240 ms, faster than 100%
of C# online submissions.
Memory Usage: 30.8 MB, less than 6.25%
of C# online submissions.
Time Complexity: O(n)
Space Complextiy: O(1)
這題我覺得蠻有意思的,第一次把題目加進Favorite
需求是將把所有 0
都放在 Array 最後
nums[i]
不為 0 時
一樣
,就不需要 swap 不一樣
,就需要 swap
,把現在這個 int 跟 pointer上記住的 0 交換pointer++
,再找尋下一個需要交換的 0以上就是這次 LeetCode 刷題的分享啦!
如果其它人有更棒的想法及意見,請留言或寄信(t4730@yahoo.com.tw) 給我。
那我們就下回見囉